import { FilterOptions } from './types';
import { ParametricEqualizer } from './ParametricEqualizer';

export function generateSamplePoints(config: {
  xMin: number;
  xMax: number;
  width: number;
  frequency: number;
}): number[] {
  const { xMin, xMax, width, frequency } = config;
  // Calculate the logarithmic ratio between xMax and xMin
  const logRatio = Math.log10(xMax / xMin);
  // Initialize an array to store the generated frequencies
  const frequencies: number[] = [];

  // Loop through each point along the width
  for (let xPos = 0; xPos < width; xPos++) {
    // Calculate the frequency at this position using logarithmic scaling
    const freq = xMin * 10 ** ((xPos / width) * logRatio);
    // Only include frequencies below half the sampling frequency to avoid aliasing
    if (freq < frequency / 2) {
      frequencies.push(Math.floor(freq));
    }
  }

  return frequencies;
}

/**
 * 根据原始频响数据 + 滤波器，计算新的频响曲线
 */
export function getFrequencyPoints(
  points: { x: number; y: number }[],
  eqs: FilterOptions[],
) {
  const PE = new ParametricEqualizer(eqs);
  const samplePoints: number[] = points.map((item) => item.x);

  const samplePointsRes = PE.calculateFrequencyResponse(samplePoints);

  return samplePointsRes.map((item, index) => {
    return {
      x: item.frequency,
      y: item.gain + points[index].y,
    };
  });
}
